package errors

import "fmt"

const (
	NoAPIDefinition = 10001 + iota
	ConfigCheckError
	ConfigCheckServerConfigWrong
	NoToMergeFile
)

const (
	DefinitionUnkownError = 10100 + iota
	DefinitionServerError
	DefinitionServerParseError
	DefinitionWellknownEmpty
)

const (
	NotifierRunError = 10200 + iota
	ReadTemplateError
	ExecTemplateError
)

const (
	SourceReadError = 10300 + iota
	SourceReadContentError
)

type Error struct {
	Code    int
	Message string
}

func (e *Error) Error() string {
	return fmt.Sprintf("[%d]%s-%s", e.Code, e.codeDes(), e.Message)
}

func (e *Error) codeDes() string {
	switch e.Code {
	case NoAPIDefinition:
		return "没有找到API定义"
	case ConfigCheckError:
		return "配置文件解析错误"
	case ConfigCheckServerConfigWrong:
		return "配置中选择Server错误"
	case DefinitionServerError:
		return "API定义文件Server定义错误"
	case DefinitionServerParseError:
		return "API定义文件Server解析错误"
	case NotifierRunError:
		return "通知组件启动错误"
	case SourceReadError:
		return "读取日志源错误"
	case SourceReadContentError:
		return "日志源内容错误"
	case DefinitionWellknownEmpty:
		return "wellknown定义文件为空"
	case NoToMergeFile:
		return "没有提供待合并文件"
	}
	return "未知错误"
}

func New(code int, msg ...string) error {
	var err = &Error{Code: code}
	if len(msg) > 0 {
		err.Message = msg[0]
	}
	return err
}

func Wrap(err error, code int) error {
	if err == nil {
		return nil
	}
	return &Error{Code: code, Message: err.Error()}
}

func Code(err error) int {
	if mye, ok := err.(*Error); ok {
		return mye.Code
	}
	return -1
}
